// pages/experience/experience.js
import throttle from '../../utils/throttle.js';
import { hasPermission } from '../../utils/tools';
import Http from '../../utils/http.js';
const http = new Http();
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        //tabbar背景
        tabbarlist: [
            {
                text: '地图',
                num: 0,
            },
            {
                text: '通答',
                num: 0,
            },
            {
                text: '经验',
                num: 0,
            },
            {
                text: '我的',
                num: 0,
            },
        ],
        tabbarActive: 2,
        current: 0,
        // 右上角胶囊的高度
        buttonHeight: '',
        // 右上角胶囊据顶部高度
        buttonTop: '',
        scrollHeight: '',
        scrollRefresh: true, //下拉刷新
        bgImg: [
            '../../images/experience/zhianyujing.png',
            '../../images/experience/zongjiao.png',
            '../../images/experience/suo.png',
            '../../images/experience/biaoqing.png',
            '../../images/experience/shandian.png',
            '../../images/experience/xingqubulas.png',
            '../../images/experience/feiji.png',
            '../../images/experience/tongyong.png',
            '../../images/experience/qita.png',
        ],
        // 经验
        pageNum: 0,
        loading: false,
        loadingAll: false,
        typeName: '',
        dotType: '',
        extypeid: '',
        experienceArr: [], // 经验数组
        experienceTotal: 0, // 经验总数
        activeExpIndex: null, // 当前经验索引
        qualityExperienceArr: [], // 精华经验
        qualityExperienceTotal: 0, // 精华经验总数
        activeQualityExpIndex: null, // 当前精华经验索引
        pageNumQualityExp: 0,
        loadingQualityExp: false,
        loadingAllQualityExp: false,
        experiencTypeArr: [], // 经验分类数组
        //操作弹框
        show: false,
        actions: [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ],
        activeCreateUid: '',
        idItem: '', // 当前经验id
        countryCount: '', //国家数
        operatorNum: Number, //运营商数量,
        showNext: false,
        permissionList: ['00', '01'],
        newsCount: 0,
        // 点击标题回到顶部
        toView: '',
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getExperienceList();
        this.getExcellentExperienceList();
        this.getExperienceTypeList();
        this.getOperatorList();
        this.getExperienceCount();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 2,
            });
            this.getTabBar().refresh();
        }

        if (app.globalData.expRefresh) {
            this.refresh();
        }
        this.getNewsNum();
    },

    refresh(refreshArr) {
        this.setData({
            pageNum: 0,
            loading: false,
            loadingAll: false,
            experienceArr: [],
            qualityExperienceArr: [],
            pageNumQualityExp: 0,
            loadingQualityExp: false,
            loadingAllQualityExp: false,
            showNext: false,
        });
        this.getExperienceTypeList();
        this.getExperienceList();
        this.getExcellentExperienceList();
        this.getOperatorList();
        this.getExperienceCount();
        this.getNewsNum();
        app.globalData.expRefresh = false;
    },

    refreshExp() {
        this.setData({
            pageNum: 0,
            loading: false,
            loadingAll: false,
            experienceArr: [],
        });
        this.getExperienceList();
        this.getExperienceTypeList();
    },

    // 刷新精华
    refreshQualityExp() {
        this.setData({
            qualityExperienceArr: [],
            pageNumQualityExp: 0,
            loadingQualityExp: false,
            loadingAllQualityExp: false,
        });
        this.getExperienceTypeList();
        this.getExcellentExperienceList();
    },

    //下拉刷新
    scrollRefresher() {
        this.setData({
            scrollRefresh: true,
        });
        this.refresh();
    },
    change(e) {
        this.setData({
            current: e.currentTarget.dataset.index,
        });
    },
    showRemark(e) {
        this.selectComponent('#bottomFrame').showFrame();
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                tabbarShow: false,
            });
        }
    },
    tabbarShow(e) {
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                tabbarShow: true,
            });
        }
    },

    // 从自定义导航栏组件中获取气泡信息
    getMenuButtonBoundingClientRect(e) {
        this.setData({
            buttonHeight: e.detail.height,
            buttonTop: e.detail.top,
        });
        let removeHeight = e.detail.top + e.detail.height + 5;
        this.getScrollHeight(removeHeight);
    },

    getScrollHeight(removeHeight) {
        var that = this;
        wx.getSystemInfo({
            success: function (res) {
                let clientHeight = res.windowHeight,
                    scrollHeight;
                // 页面高度减去需要删除的高度
                scrollHeight = clientHeight - removeHeight;

                that.setData({
                    scrollHeight: scrollHeight,
                });
            },
        });
    },

    // 编辑功能
    edit(e) {
        let { uid, id, excellentflg, index, authority } = e.detail;

        let actions = [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ];

        if (hasPermission(this.data.permissionList) || authority) {
            if (excellentflg === '00') {
                actions.splice(0, 0, {
                    name: '设置为精华',
                    color: '#333333',
                    id: 3,
                });
            } else {
                actions.splice(0, 0, {
                    name: '取消精华',
                    color: '#333333',
                    id: 4,
                });
            }

            actions.splice(2, 0, {
                name: '转移至',
                color: '#333333',
                id: 5,
            });
        }

        this.setData({
            show: true,
            activeCreateUid: uid,
            idItem: id,
            actions,
        });

        // 记录当前经验索引
        if (this.data.current == 0) {
            this.setData({
                activeExpIndex: index,
            });
        } else if (this.data.current == 1) {
            this.setData({
                activeQualityExpIndex: index,
            });
        }

        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                tabbarShow: false,
            });
        }
    },
    //取消
    onCancel(e) {
        this.setData({
            show: false,
        });
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                tabbarShow: true,
            });
        }
    },
    onSelect(e) {
        let _that = this;
        if (e.detail.id == 2) {
            wx.navigateTo({
                url: `../../releasePage/pages/addExperience/addExperience?type=01&id=${_that.data.idItem}&current=1`,
            });
            if (typeof _that.getTabBar === 'function' && _that.getTabBar()) {
                _that.getTabBar().setData({
                    tabbarShow: true,
                });
            }
        } else if (e.detail.id == 1) {
            wx.showModal({
                title: '提示',
                content: '确认要删除该项吗？',
                success: function (res) {
                    if (res.confirm) {
                        _that.deleteExperience();
                    } else {
                        console.log('点击取消回调');
                        if (
                            typeof _that.getTabBar === 'function' &&
                            _that.getTabBar()
                        ) {
                            _that.getTabBar().setData({
                                tabbarShow: true,
                            });
                        }
                    }
                },
            });
        } else if (e.detail.id == 3) {
            _that.setExperienceExcellent('01');
        } else if (e.detail.id == 4) {
            _that.setExperienceExcellent('00');
        } else if (e.detail.id == 5) {
            _that.setData({
                showNext: true,
            });
            if (typeof this.getTabBar === 'function' && this.getTabBar()) {
                this.getTabBar().setData({
                    tabbarShow: false,
                });
            }
        }
        _that.setData({
            show: false,
        });
    },
    //获取经验类别列表
    getExperienceTypeList() {
        let _that = this;
        http.getRequest(
            `cjMap/getExperienceTypeList?authId=${app.globalData.authId}`
        ).then((res) => {
            if (res.status == 0) {
                let temp = [];
                for (let i = 0; i < res.data.length; i++) {
                    let listItem = {
                        type: '',
                        count: 0,
                        iconPath: '',
                        id: '',
                    };
                    listItem.type = res.data[i].typename;
                    listItem.count = res.data[i].num;
                    listItem.id = res.data[i].id;
                    if (i > 6) {
                        if (i == res.data.length - 1) {
                            listItem.iconPath = _that.data.bgImg[8];
                        } else {
                            listItem.iconPath = _that.data.bgImg[7];
                        }
                    } else {
                        listItem.iconPath = _that.data.bgImg[i];
                    }
                    temp.push(listItem);
                }
                _that.setData({
                    experiencTypeArr: temp,
                    scrollRefresh: false,
                });
            }
        });
    },
    // 滚动到底部刷新
    onScrolltolower() {
        if (this.data.current == 0) {
            this.getExperienceList();
        } else if (this.data.current == 1) {
            this.getExcellentExperienceList();
        }
    },
    // 获取全部经验
    getExperienceList() {
        let _that = this;
        if (!_that.data.loadingAll && !_that.data.loading) {
            _that.setData({
                pageNum: _that.data.pageNum + 1,
                loading: true,
                loadingAll: false,
            });
            let data = {
                authId: app.globalData.authId,
                pageNo: _that.data.pageNum,
                pageSize: 10,
            };
            http.getRequest(`cjMap/getExperienceList`, data).then((res) => {
                if (res.status == 0) {
                    if (res.data.length) {
                        for (let i = 0; i < res.data.length; i++) {
                            res.data[i].createtime = app.timeago(
                                res.data[i].createtime
                            );
                            res.data[i].ellipsis =
                                res.data[i].content.length > 168;
                            _that.data.experienceArr.push(res.data[i]);
                        }
                    }
                    _that.setData({
                        experienceArr: _that.data.experienceArr,
                        loading: false,
                    });

                    if (res.pager.currentPage >= res.pager.totalPages) {
                        _that.setData({
                            loadingAll: true,
                        });
                    }
                } else {
                    _that.setData({
                        loadingAll: true,
                        loading: false,
                    });
                }
            });
        }
    },
    // 获取精华经验
    getExcellentExperienceList() {
        let _that = this;
        // 精华经验
        if (!_that.data.loadingAllQualityExp && !_that.data.loadingQualityExp) {
            _that.setData({
                pageNumQualityExp: _that.data.pageNumQualityExp + 1,
                loadingQualityExp: true,
                loadingAllQualityExp: false,
            });
            let data = {
                authId: app.globalData.authId,
                pageNo: _that.data.pageNumQualityExp,
                pageSize: 10,
                excellentflg: '01',
            };
            http.getRequest(`cjMap/getExperienceList`, data).then((res) => {
                if (res.status == 0) {
                    if (res.data.length) {
                        for (let i = 0; i < res.data.length; i++) {
                            res.data[i].createtime = app.timeago(
                                res.data[i].createtime
                            );
                            res.data[i].ellipsis =
                                res.data[i].content.length > 168;
                            _that.data.qualityExperienceArr.push(res.data[i]);
                        }
                    }
                    _that.setData({
                        qualityExperienceArr: _that.data.qualityExperienceArr,
                        loadingQualityExp: false,
                        qualityExperienceTotal: res.pager.totalRows,
                    });
                    if (res.pager.currentPage >= res.pager.totalPages) {
                        _that.setData({
                            loadingAllQualityExp: true,
                        });
                    }
                } else {
                    _that.setData({
                        loadingAllQualityExp: true,
                        loadingQualityExp: false,
                    });
                }
            });
        }
    },
    // 删除经验
    deleteExperience() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + `cjMap/deleteExperience`,
            method: 'GET',
            header: {
                'content-type': 'application/x-www-form-urlencoded',
            },
            data: {
                authId: app.globalData.authId,
                id: _that.data.idItem,
            },
            success: function (res) {
                if (res.data.status === '0') {
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    if (
                        typeof _that.getTabBar === 'function' &&
                        _that.getTabBar()
                    ) {
                        _that.getTabBar().setData({
                            tabbarShow: true,
                        });
                    }
                    _that.getExperienceCount();
                    if (_that.data.current == 0) {
                        _that.hiddenListItem(
                            'experienceArr',
                            _that.data.activeExpIndex
                        );
                        _that.refreshQualityExp();
                    } else if (_that.data.current == 1) {
                        _that.hiddenListItem(
                            'qualityExperienceArr',
                            _that.data.activeQualityExpIndex
                        );
                        _that.refreshExp();
                    }
                }
            },
        });
    },

    // 删除经验时，前端先隐藏这条经验而不是直接刷新
    hiddenListItem(arrName, index) {
        this.data[arrName].splice(index, 1);
        this.setData({
            [arrName]: this.data[arrName],
        });
    },

    getOperatorList() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/getCityOperatorList',
            data: {
                authId: app.globalData.authId,
                pageSize: 1,
                pageNo: 1,
            },
            success(res) {
                if (res.data.status == 0) {
                    _that.setData({
                        countryCount: res.data.countryCount,
                        operatorNum: res.data.pager.totalRows,
                    });
                }
            },
        });
    },
    // 预览图片
    previewImage(e) {
        let index = e.currentTarget.dataset.index;
        let images = JSON.parse(e.currentTarget.dataset.images) || [];

        wx.previewImage({
            current: images[index],
            urls: images,
        });
    },

    changeNav: throttle(
        (e) => {
            let { nav } = e.currentTarget.dataset;
            console.log(nav);
            wx.navigateTo({
                url: `${nav}`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    // 设为精华和取消精华
    setExperienceExcellent(excellentflg) {
        let _that = this;
        wx.request({
            url:
                app.globalData.rootPath +
                `cjMap/setExperienceExcellent?authId=${app.globalData.authId}`,
            header: {
                'content-type': 'application/json',
            },
            data: {
                excellentflg,
                id: _that.data.idItem,
            },
            success: function (res) {
                if (res.data.status == '0') {
                    const expIndex = _that.data.experienceArr.findIndex(
                        (item) => {
                            return item.id === _that.data.idItem;
                        }
                    );
                    const qualityExpIndex = _that.data.qualityExperienceArr.findIndex(
                        (item) => {
                            return item.id === _that.data.idItem;
                        }
                    );
                    if (excellentflg == '00') {
                        // 取消精华，此时这条经验在全部和精华列表中都存在，并需要在精华列表把它删掉
                        _that.setData({
                            [`experienceArr[${expIndex}].excellentflg`]: excellentflg,
                        });
                        _that.hiddenListItem(
                            'qualityExperienceArr',
                            qualityExpIndex
                        );
                        // 刷新数字点
                        _that.getExperienceCount();
                    } else {
                        // 设置精华只能在全部列表
                        if (expIndex > -1) {
                            _that.setData({
                                [`experienceArr[${expIndex}].excellentflg`]: excellentflg,
                            });
                        }
                        // 这条经验需要刷新才能在精华列表中出现
                        _that.refreshQualityExp();
                    }
                }
                if (
                    typeof _that.getTabBar === 'function' &&
                    _that.getTabBar()
                ) {
                    _that.getTabBar().setData({
                        tabbarShow: true,
                    });
                }
            },
        });
    },

    // 经验转为其他类型，页面不刷新，只是隐藏
    handleChangeExperience() {
        // 刷新数字点
        this.getExperienceCount();
        this.getExperienceTypeList();
        if (this.data.current == 0) {
            this.hiddenListItem('experienceArr', this.data.activeExpIndex);
            this.refreshQualityExp();
        } else if (this.data.current == 1) {
            this.hiddenListItem(
                'qualityExperienceArr',
                this.data.activeQualityExpIndex
            );
            this.refreshExp();
        }
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                tabbarShow: true,
            });
        }
    },

    // 获取经验数字
    getExperienceCount() {
        let data = {
            authId: app.globalData.authId,
        };
        http.getRequest(`cjMap/getExperienceCount`, data).then((res) => {
            if (res.status == '0') {
                this.setData({
                    experienceTotal: res.totalcount,
                    qualityExperienceTotal: res.exellentcount,
                });
            }
        });
    },

    // 转移上一步
    upBtn(e) {
        this.setData({
            showNext: false,
            show: true,
        });
        this.tabbarShow();
    },

    hideTranferCover(e) {
        this.setData({
            showNext: false,
        });
        this.tabbarShow();
    },

    // 处理点赞同步问题
    handleLike(e) {
        let { id, praiseflg, praisecnt } = e.detail;
        let expIndex = -1;
        let qualityExpIndex = -1;
        this.data.experienceArr.map((item, index) => {
            if (item.id === id) {
                expIndex = index;
            }
        });
        this.data.qualityExperienceArr.map((item, index) => {
            if (item.id === id) {
                qualityExpIndex = index;
            }
        });
        if (expIndex > -1) {
            this.setData({
                [`experienceArr[${expIndex}].praiseflg`]: praiseflg,
                [`experienceArr[${expIndex}].praisecnt`]: praisecnt,
            });
        }
        if (qualityExpIndex > -1) {
            this.setData({
                [`qualityExperienceArr[${qualityExpIndex}].praiseflg`]: praiseflg,
                [`qualityExperienceArr[${qualityExpIndex}].praisecnt`]: praisecnt,
            });
        }
    },

    // 点击评论图标直接跳转到底部评论区
    handleComment: throttle(
        (e) => {
            const { id } = e.detail;
            wx.navigateTo({
                url: `../../functionPage/pages/experienceDetail/experienceDetail?id=${id}&comment=1`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    // 刷新某一条经验的评论数
    refreshCommentNum(params) {
        const { id, commentcount } = params;
        const expIndex = this.data.experienceArr.findIndex((item) => {
            return item.id === id;
        });
        const qualityExpIndex = this.data.qualityExperienceArr.findIndex(
            (item) => {
                return item.id === id;
            }
        );
        if (expIndex > -1) {
            this.setData({
                [`experienceArr[${expIndex}].commentcount`]: commentcount,
            });
        }
        if (qualityExpIndex > -1) {
            this.setData({
                [`qualityExperienceArr[${qualityExpIndex}].commentcount`]: commentcount,
            });
        }
    },

    // 获取消息数量
    getNewsNum() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/getUnreadMsgCnt',
            header: {
                'content-type': 'application/json',
            },
            data: {
                authId: app.globalData.authId,
            },
            success(res) {
                console.log(res.data.data);
                app.globalData.nqModuleCount = res.data.data.nqModuleCount;
                app.globalData.exModuleCount = res.data.data.exModuleCount;
                app.globalData.mineModuleCount = res.data.data.mineModuleCount;
                let arr1 = 'tabbarlist[1].num';
                let arr2 = 'tabbarlist[2].num';
                let arr3 = 'tabbarlist[3].num';
                _that.setData({
                    [arr1]: res.data.data.nqModuleCount,
                    [arr2]: res.data.data.exModuleCount,
                    [arr3]: res.data.data.mineModuleCount,
                    newsCount: res.data.data.exModuleCount,
                });
                if (
                    typeof _that.getTabBar === 'function' &&
                    _that.getTabBar()
                ) {
                    _that.getTabBar().setData({
                        selected: 2,
                        tabbarShow: true,
                    });
                    _that.getTabBar().refresh();
                }
            },
        });
    },
    onTabbarChange(event) {
        this.setData({ active: event.detail });
        let url;
        if (event.detail == 0) {
            url = '/pages/index/index';
        }
        if (event.detail == 1) {
            url = '/pages/notice/notice';
        }
        if (event.detail == 2) {
            url = '/pages/experience/experience';
        }
        if (event.detail == 3) {
            url = '/pages/minePage/minePage';
        }
        wx.switchTab({
            url: url,
        });
    },
    // 点击标题回到顶部
    doubleTap() {
        this.setData({
            toView: 'experience-area',
        });
    },
});
